package com.sunshine.lnuplus.internet

import android.content.Context
import com.sunshine.lnuplus.callback.LoadDataCallBack
import com.sunshine.lnuplus.service.LoadWeatherService
import okhttp3.*
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException

class LoadWeather(
    private val service: LoadWeatherService,
    private var callBack: LoadDataCallBack
) {

    init {
        loadWeather()
    }

    /**
     * 下载天气
     */
    private fun loadWeather() {
        val url = "https://www.tianqiapi.com/api/?version=v6&ip&appid=84958684&appsecret=gHjgc8wG"
        val okHttpClient = OkHttpClient()
        val request = Request.Builder().url(url).build()
        val call = okHttpClient.newCall(request)
        call.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                service.stopSelf()
            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                ResolveWeather(response.body!!.string())
            }
        })
    }

    //解析weather的json信息
    private fun ResolveWeather(WeatherData: String) {
        try {
            val edit = service.getSharedPreferences("weather", Context.MODE_PRIVATE).edit()
            val jsonObject = JSONObject(WeatherData)
            val city = jsonObject.getString("city")
            val tem = jsonObject.getString("tem")
            val weather = jsonObject.getString("wea")
            val update_time = jsonObject.getString("update_time")
            val tem1 = jsonObject.getString("tem1")
            val tem2 = jsonObject.getString("tem2")
            val win = jsonObject.getString("win")
            val win_speed = jsonObject.getString("win_speed")
            val humidity = jsonObject.getString("humidity")
            val air = jsonObject.getString("air")
            edit.apply {
                putString("city", city)
                putString("tem", tem)
                putString("weather", weather)
                putString("update_time", update_time)
                putString("tem1", tem1)
                putString("tem2", tem2)
                putString("win", win)
                putString("win_speed", win_speed)
                putString("humidity", humidity)
                putString("air", air)
                putInt("lastDay", com.sunshine.lnuplus.utils.DateUtils.day)
                putInt("lastHour", com.sunshine.lnuplus.utils.DateUtils.hour)
                putInt("lastMinute", com.sunshine.lnuplus.utils.DateUtils.minute)
                apply()
            }
            callBack.onSuccess()
        } catch (e: JSONException) {
            e.printStackTrace()
        }
    }
}